/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*局域网TCP客户端*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <Client.h>
#include "hilog_wrapper.h"
 
#define MYPORT  8890
#define BUFFER_SIZE 1024


BearSocketMgr::BearSocketMgr(){
    HILOG_INFO("[Car Controller] Core init");
};
BearSocketMgr::~BearSocketMgr(){
    HILOG_INFO("[Car Controller] Core destroyed");
};
 
void BearSocketMgr::Start(){	
   // int sock_client;//客户端套接字  
    int len;  
    //int sin_size;
    //char buf[BUFSIZ];  //数据传送的缓冲区
    struct sockaddr_in remote_addr; //客户端网络地址结构体 
    HILOG_INFO("[Car Controller] Core Connect calBear");
    ///定义sockfd
    sock_server = socket(AF_INET,SOCK_STREAM, 0); 
    ///定义sockaddr_in
    struct sockaddr_in servaddr;//服务器网络地址结构体
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8890);  //服务器端口
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);  //服务器ip，inet_addr用于IPv4的IP转换（十进制转换为二进制）
    //连接服务器
    if(int ret =  bind(sock_server,(sockaddr*)&servaddr,sizeof(servaddr)) < 0)
    {
         //connectionStatus = 0;
        HILOG_INFO("[Bear Controller] Core Connection fail");
        return;
    }
    else{
        //connectionStatus = 1;
        HILOG_INFO("[Bear Controller] Core Connection success");
        //return;
    }
    if (listen(sock_server, 20) == -1)
	{
		HILOG_INFO("[Bear Controller] listen Connection fail");
	}

    // if (connect(sock_client, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    // {
    //     connectionStatus = 0;
    //     HILOG_INFO("[Car Controller] Core Connection fail");
    //     return;
    // }
    // else{
    //     connectionStatus = 1;
    //     HILOG_INFO("[Car Controller] Core Connection success");
    //     return;
    // }
   	
	//sin_size = sizeof(struct sockaddr_in);
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
   
      if((sock_client=accept(sock_server,(struct sockaddr *)&remote_addr,&clnt_addr_size))<0)  
    {  
        connectionStatus = 0;
        HILOG_INFO("[Bear Controller] accept Connection fail");
        return;  
    } else{
        HILOG_INFO("[Bear Controller] accept Connection succ");
         connectionStatus = 1;
    }
       
	if((len=send(sock_client,"Welcome to my server/n",21,0))<0)//发送欢迎信息  
    {
        HILOG_INFO("[Bear Controller] send fail");
    }
		// while (1)
		// {
		// 	if ((ret = recv(new_fd, recvbuf, sizeof(recvbuf), 0)) == -1)
		// 	{
		// 		printf("recv error \r\n");
		// 	}
		// 	printf("recv :%s\r\n", recvbuf);
		// 	sleep(2);
		// 	if ((ret = send(new_fd, buf, strlen(buf) + 1, 0)) == -1)
		// 	{
		// 		perror("send : ");
		// 	}

		// 	sleep(2);
		// }
		// close(new_fd);
	// if((len=recv(sock_client,buf,BUFSIZ,0))<0)
    // {
    //     HILOG_INFO("[Bear Controller] receive Connection fail");
    // }
    //  printf("%s/n",buf);  
    //tcpServerInit(MYPORT);
};
// TCPServer* tcpServerInit(int port){
//     // Initialize server socket..
//     TCPServer* tcpServer = new TCPServer();
    
//     // When a new client connected:
//     tcpServer->onNewConnection = [&](TCPSocket *newClient) {
//         cout << "New client: [";
//         cout << newClient->remoteAddress() << ":" << newClient->remotePort()<< "]" << endl;
//         newClient->onMessageReceived = [newClient, this](string message) {
//             connectionStatus = 1;
//             cout << newClient->remoteAddress() << ":" << newClient->remotePort() << " => " << message << endl;
//             newClient->Send("TeamInfo Server COPY!");
//         };
        
//         // If you want to use raw bytes
//         /*
//         newClient->onRawMessageReceived = [newClient](const char* message, int length) {
//             cout << newClient->remoteAddress() << ":" << newClient->remotePort() << " => " << message << "(" << length << ")" << endl;
//             newClient->Send("OK!");
//         };
//         */
        
//         newClient->onSocketClosed = [newClient]() {
//             cout << "Socket closed:" << newClient->remoteAddress() << ":" << newClient->remotePort() << endl;
//         };
//     };

//     // Bind the server to a port.
//     tcpServer->Bind(port, [](int errorCode, string errorMessage) {
//         // BINDING FAIBear:
//         cout << errorCode << " : " << errorMessage << endl;
//     });

//     // Start Listening the server.
//     tcpServer->Listen([](int errorCode, string errorMessage) {
//         // LISTENING FAIBear:
//         cout << errorCode << " : " << errorMessage << endl;
//     });
//     return tcpServer;
// };
void BearSocketMgr::Send(char* strdata){
    HILOG_INFO("[Bear Controller] Core Send calBear, the data is: %s", strdata);
    //如果没有连接，返回错误信息并退出
    if (connectionStatus != 1){
        HILOG_INFO("[Bear Controller] Core Send fail, not connected");
        sendStatus = -1;
        return;
    };
    //发送
    sendStatus = send(sock_client, strdata, strlen(strdata),0);
    if (sendStatus == -1){
        HILOG_INFO("[Bear Controller] Core Send fail");
    }
    else{
        HILOG_INFO("[Bear Controller] Core Send success");
    }
    return;
};

void BearSocketMgr::Close(){
    HILOG_INFO("[Bear Controller] Core Close calBear");
    close(sock_server);
    close(sock_client);
    return;
};


int32_t BearSocketMgr::GetConnectionStatus(){
    return BearSocketMgr::connectionStatus;
};


int32_t BearSocketMgr::GetSocketClient(){
    return BearSocketMgr::sock_client;
};

int32_t BearSocketMgr::GetSendStatus(){
    return BearSocketMgr::sendStatus;
};
